package com.wzy.authority.service.impl;

import com.wzy.authority.base.dto.LoginUser;
import com.wzy.authority.domain.SysPermission;
import com.wzy.authority.domain.SysUser;
import com.wzy.authority.service.SysPermissionService;
import com.wzy.authority.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @program: authorityManagement
 * @description: 实现security用户服务类,让验证逻辑走我们自己流程
 * @author: 1
 * @create: 2020-03-24 20:41
 **/
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserService sysUserServiceImpl;

    @Resource
    private SysPermissionService sysPermissionServiceImpl;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserServiceImpl.selectUserByName(username);
        //没有找到该用户
        if(sysUser == null){
            throw new AuthenticationCredentialsNotFoundException("用户不存在");
        }
        //该用户帐号异常
        else if(SysUser.Status.DISABLED.equals(sysUser.getStatus())){
            throw new LockedException("你的账户被冻结");
        }
        //该账户被锁定
        else if(SysUser.Status.LOCKED.equals(sysUser.getStatus())){
            throw new LockedException("你的账户被锁定,请联系管理员");
        }

        //创建LoginUser,然后将sysUser复制到LoginUser
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(sysUser,loginUser);

        //通过服务  使用userId获取用户权限列表
        List<SysPermission> sysPermissions = sysPermissionServiceImpl.listByUserId(sysUser.getId());

        //将用户权限列表装入loginUser中
        loginUser.setSysPermissions(sysPermissions);

        //返回loginUser   可以的原因是loginUser实现UserDetails
        return loginUser;
    }
}
